package com.dqv5.shorturl.controller;

import com.alibaba.fastjson.JSONObject;
import com.dqv5.shorturl.exception.CommonShortException;
import com.dqv5.shorturl.service.MainService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * @author duqian
 * @date 2020/6/4
 */
@RestController
@RequestMapping("/api")
public class ApiController {

    @Value("${shorturl.host}")
    private String shorUrlHost;

    @Autowired
    private MainService mainService;

    /**
     * 添加url映射
     *
     * @return
     */
    @PostMapping("/short")
    public ResponseEntity<?> add(@RequestBody JSONObject param) {
        String url = param.getString("url");
        if (StringUtils.isBlank(url)) {
            throw new CommonShortException("url不能为空！");
        }
        String code = mainService.shortUrl(url);
        if (shorUrlHost.endsWith("/")) {
            shorUrlHost = shorUrlHost.substring(0, shorUrlHost.length() - 1);
        }
        String shortUrl = shorUrlHost + "/t/" + code;
        JSONObject result = new JSONObject();
        result.put("origin", url);
        result.put("short", shortUrl);
        return ResponseEntity.ok(result);
    }
}
